<?php

namespace  app\command\controller;

use common\model\sell66\OutTrade;
use common\model\sell66\BotInv;
use common\bot\SteamBotService;
use think\Exception;

/**
 * 检查取回报价状态
 * 
 * @author zhouqiang
 * @date 2018-06-05
 */
class CheckOutTrade
{

	protected function getOutTradeByCheckAll()
	{
		return OutTrade::getOutTradeByCheckAll();
	}

	protected function rpcCheckOut($tradeofferoutId)
	{
		return SteamBotService::getInstance()->rpcCheckOut($tradeofferoutId);
	}

	protected function updateOutTrade($outTradeId, $tradeofferId, $tradeofferStatus, $details)
	{
		return OutTrade::updateOutTrade($outTradeId, $tradeofferId, $tradeofferStatus, $details);
	}

	protected function updateTimeOutTrade($outTradeId, $tradeofferStatus, $details)
	{
		return OutTrade::updateTimeOutTrade($outTradeId, $tradeofferStatus, $details);
	}

	protected function checkTradeAll()
	{
		$trades = $this->getOutTradeByCheckAll();
		if (!$trades) {
			echo 'query waiting check for out trade failed'."\r\n";
			return false;
		}

		foreach ($trades as $trade) {
			if ($trade['tradeoffer_out_id'] <= 0) {
				$res = $this->timeOutTrade($trade['out_trade_id'], $trade['tradeoffer_status'], $trade['created_at'], $trade['out_trade_detail']);
				if ($res) {
					echo 'query out trade timeout, out_trade_id: '.$trade['out_trade_id']."\r\n";
				}
				continue;
			}
			$this->checkTrade($trade['out_trade_id'], $trade);
		}
		
		return true;
	}

	protected function timeOutTrade($outTradeId, $tradeState, $createdAt, $details)
	{
		// 报价超时
		if ($tradeState == OutTrade::$tradeStatusMap['reading']) {
			if (strtotime($createdAt) < (time() - 300)) {
				$res = $this->updateTimeOutTrade($outTradeId, OutTrade::$tradeStatusMap['time-out'], $details);
				if (!$res) {
					echo 'update out trade status failed, out_trade_id: '.$outTradeId."\r\n";
				}
				return true;
			}
		}

		return false;
	}

	protected function checkTrade($outTradeId, array $trade)
	{
		$res = $this->rpcCheckOut($trade['tradeoffer_out_id']);
		if (!$res['code']) {
			echo 'query trade status failed, tradeoffer_out_id:'.$trade['tradeoffer_out_id']."\r\n";
			return false;
		}

		$data = $res['data'];

		$tradeofferId = $data['tradeoffer_id'];
		$status = $data['tradeoffer_status'];
		$details = $trade['out_trade_detail'];

		if ($trade['tradeoffer_status'] == $status) {
			echo 'no change in the trade status, out_trade_id: '.$outTradeId."\r\n";
			return false;
		}

		$res = $this->updateOutTrade($outTradeId, $tradeofferId, $status, $details);
		if (!$res) {
			echo 'update out trade failed, out_trade_id: '.$outTradeId."\r\n";
			return false;
		}
		echo 'update out trade success, out_trade_id: '.$outTradeId."\r\n";

		return true;
	}

	public function handle()
	{
		$this->checkTradeAll();
		echo '数据查询完毕！'."\r\n";
		return true;
	}
}